//
//  DataBaseSimple.m
//  SimpleDemo
//
//  Created by 毛志 on 14-2-18.
//  Copyright (c) 2014年 maozhi. All rights reserved.
//

#import "DataBaseSimple.h"

static DataBaseSimple * simple = nil;

@implementation DataBaseSimple
{
    FMDatabase * _dataBase;
}

+ (DataBaseSimple *)sharedDataBase
{
    if (simple == nil) {
        simple = [[DataBaseSimple alloc] init];
    }
    return simple;
}

- (id)init
{
    self = [super init];
    if (self) {
        NSArray * arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * path = [arr objectAtIndex:0];
        path = [path stringByAppendingPathComponent:@"Test.db"];
        NSLog(@"path is %@...",path);
        _dataBase = [FMDatabase databaseWithPath:path];
        if (![_dataBase open]) {
            NSLog(@"can not open dataBase!");
            return nil;
        }
        
        [_dataBase executeUpdate:@"CREATE TABLE if not exists TableOne (Num integer PRIMARY KEY AUTOINCREMENT,ID text,Name text,Summary text,Read text)"];
    }
    return self;
}

- (BOOL)insertDataToDataBase:(QFBookModel *)model andKey:(NSInteger)key
{
    return [_dataBase executeUpdate:@"INSERT INTO TableOne (Num,ID,Name,Summary,Read) VALUES (?,?,?,?,?)",[NSNumber numberWithInt:key],model.bookID,model.bookName,model.bookSummary,model.bookRead];
}

- (BOOL)deleteDataFromDataBaseForKey:(NSInteger)key
{
    return [_dataBase executeUpdate:@"DELETE FROM TableOne WHERE Num=?",[NSNumber numberWithInt:key]];
}

- (BOOL)updateDataFromDataBase:(QFBookModel *)model andKey:(NSInteger)key
{
    return [_dataBase executeUpdate:@"UPDATE TableOne SET ID=?,Name=?,Summary=?,Read=? WHERE Num=?",model.bookID,model.bookName,model.bookSummary,model.bookRead,[NSNumber numberWithInt:key]];
}

- (QFBookModel *)selectFromDataBaseForKey:(NSInteger)key
{
    FMResultSet * rs = [_dataBase executeQuery:@"SELECT * FROM TableOne WHERE Num=?",[NSNumber numberWithInt:key]];
    QFBookModel * model = [[QFBookModel alloc] init];
    [rs next];
    model.bookID = [rs stringForColumn:@"ID"];
    model.bookName = [rs stringForColumn:@"Name"];
    model.bookSummary= [rs stringForColumn:@"Summary"];
    model.bookRead = [rs stringForColumn:@"Read"];
    return model;
}

- (NSMutableArray *)selectAllDataFromDataBase
{
    FMResultSet * rs = [_dataBase executeQuery:@"SELECT * FROM TableOne"];
    NSMutableArray * arr = [NSMutableArray array];
    while ([rs next]) {
        QFBookModel * model = [[QFBookModel alloc] init];
        model.bookID = [rs stringForColumn:@"ID"];
        model.bookName = [rs stringForColumn:@"Name"];
        model.bookSummary= [rs stringForColumn:@"Summary"];
        model.bookRead = [rs stringForColumn:@"Read"];
        [arr addObject:model];
    }
    return arr;
}

// 清空table表
- (BOOL)dropTable
{
    return [_dataBase executeUpdate:@"DELETE FROM TableOne"];
}


//- (BOOL)deleteTable
//{
//    return [_dataBase executeUpdate:@"drop table TableOne"];
//}

@end
